﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using SW.Lite.IDAL.Master;
using SW.Lite.Infrastructure.Common;
using SW.Lite.Infrastructure.Helpers;
using SW.Lite.Model.Master;

namespace SW.Lite.DAL.MsSql.Master
{
    public class Menu : IMenu
    {
        public bool Exists(int id)
        {
            const string sql = "SELECT COUNT(1) FROM SW_M_Menu WHERE Id=@Id";
            var paramter = new SqlParameter("@Id", SqlDbType.Int) { Value = id };
            return MsSqlHelper.Exists(sql, paramter);
        }

        public MenuModel Single(int id)
        {
            const string sql =
                "SELECT Id, ParentID, Code, Title, Icon, ControllerName, ActionName, Sort FROM SW_M_Menu WHERE Id=@Id";

            var paramter = new SqlParameter("@Id", SqlDbType.Int) { Value = id };
            return FillSingle(sql, paramter);
        }

        public PageList<MenuModel> All()
        {
            const string sql = "SELECT Id, ParentID, Code, Title, Icon, ControllerName, ActionName, Sort FROM SW_M_Menu";

            return FillList(sql);
        }

        public PageList<MenuModel> All(int parentId, int pageIndex, int pageSize)
        {
            var start = (pageIndex - 1) * pageSize;
            var end = pageIndex * pageSize;

            var sql = string.Format(@"SELECT Id, ParentID, Code, Title, Icon, ControllerName, ActionName, Sort FROM (SELECT ROW_NUMBER() OVER (ORDER BY Sort) ROWNO, * FROM SW_M_Menu WHERE SW_M_Menu.ParentID={2}) A WHERE A.ROWNO BETWEEN {0} AND {1};
SELECT COUNT(1) FROM SW_M_Menu WHERE ParentID={2};", start, end, parentId);

            return FillList(sql);
        }

        public ExecuteResult Insert(MenuModel model)
        {
            const string sql = "INSERT INTO SW_M_Menu(ParentID, Code, Title, Icon, ControllerName, ActionName, Sort) VALUES (@ParentID, @Code, @Title, @Icon, @ControllerName, @ActionName, @Sort)";

            var parameters = new[]
            {
                new SqlParameter("@ParentID", SqlDbType.Int) {Value = model.ParentID},
                new SqlParameter("@Code", SqlDbType.NVarChar) {Value = model.Code},
                new SqlParameter("@Title", SqlDbType.NVarChar) {Value = model.Title},
                new SqlParameter("@Icon", SqlDbType.NVarChar) {Value = model.Icon},
                new SqlParameter("@ControllerName", SqlDbType.NVarChar) {Value = model.ControllerName},
                new SqlParameter("@ActionName", SqlDbType.NVarChar) {Value = model.ActionName},
                new SqlParameter("@Sort", SqlDbType.Int) {Value = model.Sort}
            };

            var result = MsSqlHelper.Execute(sql, parameters);
            return 0 == result ? new ExecuteResult(false) : new ExecuteResult(true);
        }

        public ExecuteResult Update(MenuModel model)
        {
            const string sql = "UPDATE SW_M_Menu SET ParentID=@ParentID, Code=@Code, Title=@Title, Icon=@Icon, ControllerName=@ControllerName, ActionName=@ActionName, Sort=@Sort WHERE Id=@Id ";
            var parameters = new[]
            {
                new SqlParameter("@Id", SqlDbType.Int) {Value = model.Id},
                new SqlParameter("@ParentID", SqlDbType.Int) {Value = model.ParentID},
                new SqlParameter("@Code", SqlDbType.NVarChar) {Value = model.Code},
                new SqlParameter("@Title", SqlDbType.NVarChar) {Value = model.Title},
                new SqlParameter("@Icon", SqlDbType.NVarChar) {Value = model.Icon},
                new SqlParameter("@ControllerName", SqlDbType.NVarChar) {Value = model.ControllerName},
                new SqlParameter("@ActionName", SqlDbType.NVarChar) {Value = model.ActionName},
                new SqlParameter("@Sort", SqlDbType.Int) {Value = model.Sort}
            };

            var result = MsSqlHelper.Execute(sql, parameters);
            return 0 == result ? new ExecuteResult(false) : new ExecuteResult(true);
        }

        public ExecuteResult UpdateSort(Dictionary<int, int> menuSorts)
        {
            var sqlBuilder = new StringBuilder();
            foreach (var item in menuSorts)
                sqlBuilder.AppendLine(String.Format("UPDATE SW_M_Menu SET Sort={1} WHERE Id={0}", item.Key, item.Value));

            var result = MsSqlHelper.Execute(sqlBuilder.ToString());
            return 0 == result ? new ExecuteResult(false) : new ExecuteResult(true);
        }

        public ExecuteResult Delete(params int[] ids)
        {
            if (ids == null || ids.Length <= 0)
                return new ExecuteResult { Result = false, Message = "删除失败" };

            var idStr = ids.Select(n => n.ToString());

            var sql = "DELETE FROM SW_M_Menu WHERE Id IN (" + String.Join(",", idStr) + ")";
            var result = MsSqlHelper.Execute(sql);
            return 0 == result ? new ExecuteResult(false) : new ExecuteResult(true);
        }

        public PageList<MenuModel> GetMenusByRoleIds(params int[] roleIDs)
        {
            if (roleIDs == null || roleIDs.Length <= 0)
                return new PageList<MenuModel>();

            var ids = roleIDs.Select(n => n.ToString());

            var sql = "SELECT Id, ParentID, Code, Title, Icon, ControllerName, ActionName, Sort FROM SW_M_Menu WHERE Id IN(SELECT MenuID FROM SW_M_MenuRole WHERE RoleID IN ('" + String.Join("','", ids) + "'))";

            return FillList(sql);
        }

        public MenuModel GetMenuByCode(string code)
        {
            const string sql = "SELECT Id, ParentID, Code, Title, Icon, ControllerName, ActionName, Sort FROM SW_M_Menu WHERE Code=@Code";
            var paramter = new SqlParameter("@Code", SqlDbType.NVarChar) { Value = code };

            return FillSingle(sql, paramter);
        }

        private MenuModel FillSingle(string sql, params SqlParameter[] paramters)
        {
            MenuModel data = null;
            using (var rdr = MsSqlHelper.ExecuteReader(sql, paramters))
            {
                if (rdr.Read())
                    data = ReadData(rdr);
            }
            return data;
        }

        private PageList<MenuModel> FillList(string sql, params SqlParameter[] paramters)
        {
            var list = new PageList<MenuModel>();
            using (var rdr = MsSqlHelper.ExecuteReader(sql, paramters))
            {
                while (rdr.Read())
                    list.Add(ReadData(rdr));
                if (rdr.NextResult() && rdr.Read())
                    list.AllCount = rdr.GetInt32(0);
                else
                    list.AllCount = list.Count;
            }
            return list;
        }

        private MenuModel ReadData(SqlDataReader dr)
        {
            return new MenuModel
            {
                Id = Convert.ToInt32(dr["Id"]),
                ParentID = Convert.ToInt32(dr["ParentID"]),
                Code = Convert.ToString(dr["Code"]),
                Title = Convert.ToString(dr["Title"]),
                Icon = Convert.ToString(dr["Icon"]),
                ControllerName = Convert.ToString(dr["ControllerName"]),
                ActionName = Convert.ToString(dr["ActionName"]),
                Sort = Convert.ToInt32(dr["Sort"])
            };
        }
    }
}